<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\facade\Db;

/**
 * 商品品牌
 */
class Brand extends Backend {
    /**
     * Brand模型对象
     * @var object
     * @phpstan-var \app\admin\model\goods\Brand
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

    protected string|array $quickSearchField = ['name', 'style'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\admin\model\goods\Brand;
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $data['outstation_id'] = $this->outstation['id'];

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit(): void {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if(empty($data['supply_rate'])){
                $data['supply_rate'] = null;
            }else{
                if($data['supply_rate'] > 100) $this->error('供货率不能大于100%');
                if($data['supply_rate'] < 0) $this->error('供货率不能为负数');
            }

//            print_r($data);die;

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($data);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }

        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 获取全部品牌
     */
    public function getAllBrand() :void{
        $param = $this->request->param();
        $where = [
            ['outstation_id', '=', $this->outstation['id']]
        ];
        $result = Db::name('goods_brand')->field('id, name')->where($where)->select()->toArray();
        $user_supply = db::name('user_brand_profit')->where(['user_id' => $param['user_id']])->select()->toArray();
        foreach($result as $key => $val){
            foreach($user_supply as $v){
                if($val['id'] == $v['brand_id']){
                    $result[$key]['value'] = $v['profit'];
                }
            }
        }
        $this->success('', $result);
    }

    /**
     * 列表
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $custom_where = [
            ['outstation_id', '=', $this->outstation['id']]
        ];


        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($custom_where)
            ->order($order)
            ->paginate($limit);


        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function userBrand(): void {

        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        $param = $this->request->param();
        if(empty($param['user_id'])){
            $this->success('', [
                'list' => [],
                //            'total' => $res->total(),
                'remark' => get_route_remark(),
            ]);
            $this->error('请先选择客户');
        }

        $user_brand = Db::name('user_brand_profit')->where(['user_id' => $param['user_id']])->select();
        $brand_ids = [];
        foreach($user_brand as $val) $brand_ids[] = $val['brand_id'];

//        print_r($brand_ids);die;

        $custom_where = [
            ['id', 'in', $brand_ids]
        ];


        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where($custom_where)
            ->order($order)
            ->select();


        $this->success('', [
            'list' => $res,
//            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}